﻿using System;
using System.Collections.Generic;
using System.Text;
 
using Model;

using System.Data;
using System.IO;
using Utility;


using IBLL.Controller;
using IBLL.View;
using System.Windows.Forms;
using DALFactory.DataBase;

namespace BLL.Controller
{
    public class FormControllerBase : IFormController
    {
       
        

        public IViewForm view { get; set; }

        private string table_=string.Empty;
        private string xml_=string.Empty;
       
        protected virtual string Table {
            get { return table_; }
           
        }
        protected virtual string XmlName
        {
            get { return xml_; }

        }
        private EntityState state_;
        private EntityKey dataEntity_;
        private EntityKey PrimaryKey_;
        public virtual object OnLoad(EntityKey key)
        {
            PrimaryKey_ = key;
            if (key != null && key.ToString() != string.Empty && key.Keys.Count > 0 && !string.IsNullOrEmpty(Convert.ToString(key.Keys[0].Value)))
            {
                string strSelect = string.Format("select * from {0} where {1}", Table, key.ToString());
                DataSet ds = new DataSet(); //access.GetDataSet(System.Data.CommandType.Text, strSelect);
                if (ds == null || ds.Tables[0].Rows.Count == 0)
                {
                    throw new Exception(string.Format("not exist {0} ",key.ToString()));
                }
                else
                    DataSetToObject(ds.Tables[0].Rows[0]);
                SetState(EntityState.Edit);
            }
            else
                DataSetToObject(null);                 
            return dataEntity_;
        }
        public void OnCreate()
        {
            PrimaryKey_ = null;
            DataSetToObject(null);
            SetState(EntityState.New);
        }
        public virtual void OnDelete(EntityKey key)
        {
            string strDel = string.Format("delete from {0} where {1}", Table, PrimaryKey_.ToString());
            //access.ExecuteNonQuery(System.Data.CommandType.Text, strDel);
        }
        public virtual void OnUpdate()
        {
            PrimaryKey_.Keys = new List<ColumnDefine>();
            string str = string.Empty;
             string condition = string.Empty;
             foreach (ColumnDefine column in dataEntity_.Keys)
             {
                 //if (!column.PrimaryKey)
                 //    str += string.Format(",{0}", column.ToString());
                 //else
                 //{
                 //    PrimaryKey_.Keys.Add(column);
                 //    condition += string.Format("and {0} ", column.ToString());
                 //}
             }
            if (str.Trim().StartsWith(","))
                str = str.Trim().Substring(1);
           
            
            if (condition.Trim().StartsWith("and"))
                condition = condition.Trim().Substring(3);

            string strSql = string.Format("update {0} set {1} where {2}", Table, str, condition);
           
            //access.ExecuteNonQuery(System.Data.CommandType.Text, strSql);
            SetState(EntityState.Edit);
        }
        public virtual void OnSave()
        {
            
            string col = string.Empty;
            string data = string.Empty;
            foreach (ColumnDefine column in dataEntity_.Keys)
            {
            //    if (column.PrimaryKey)
            //    {
            //        PrimaryKey_ = new EntityKey();
            //        PrimaryKey_.Keys.Add(column);
            //    }
            //    col += string.Format(",{0}", column.Column);
            //    if (column.Type == DataType.INT)
            //        data += string.Format(",{0}", column.Value);
            //    else
                    //data += string.Format(",'{0}'", column.Value);
            }
            if (col.Trim().StartsWith(","))
                col = col.Trim().Substring(1);
            if (data.Trim().StartsWith(","))
                data = data.Trim().Substring(1);

            string strSql = string.Format("insert into {0} ({1} )values({2})", Table, col, data);
            //access.ExecuteNonQuery(System.Data.CommandType.Text, strSql);
            SetState(EntityState.Edit);
        }
        public virtual void OnGetValue(Control c)
        {
            DataSetHelper.GetValue(dataEntity_.Keys, c);
          
        }


        public virtual void OnSetValue(Control c)
        {
            DataSetHelper.RowToObject(dataEntity_.Keys, c);
        }
        private  void SetState(EntityState state)
        {
            state_ = state;
        }
        public EntityState GetState()
        {
            return state_;
        }
        private void DataSetToObject(DataRow dr)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, string.Format("Config{0}Mapping{0}{1}", Path.DirectorySeparatorChar,XmlName));
            if (File.Exists(path))
            {
                if (dataEntity_ == null)
                    dataEntity_ = new EntityKey();
                dataEntity_.Keys = XmlReadWriteHelper.Deserialize(typeof(List<ColumnDefine>), path) as List<ColumnDefine>;

                int Length = dataEntity_.Keys.Count;
                if (dr != null)
                {
                    for (int i = 0; i < Length; i++)
                    {
                        dataEntity_.Keys[i].Value = dr[dataEntity_.Keys[i].Column];
                    }
                }

            }
            else
                throw new Exception("file not exist");
        }

        #region IFormController 成员

        public void Show()
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}